#!/usr/bin/python3
# ******************************************************************************
# Copyright (c) Huawei Technologies Co., Ltd. 2020-2020. All rights reserved.
# licensed under the Mulan PSL v2.
# You can use this software according to the terms and conditions of the Mulan PSL v2.
# You may obtain a copy of Mulan PSL v2 at:
#     http://license.coscl.org.cn/MulanPSL2
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
# PURPOSE.
# See the Mulan PSL v2 for more details.
# ******************************************************************************/

import os
from itertools import zip_longest
from pathlib import Path


class ComparePatch:
    def __init__(self) -> None:
        self.content = ""
        self.to_compare_content = ""

    def _get_content(self, str_or_filepath):
        """get param content

        Args:
            str_or_filepath (any): str or Pathlike to read you content

        Raises:
            ValueError: Check you params Please
            FileNotFoundError: Check you params Please,if it is Path

        Returns:
            str: your param content
        """

        if (
            isinstance(str_or_filepath, os.PathLike)
            or Path(str_or_filepath).is_absolute()
        ):
            with open(str_or_filepath, "r", encoding="utf-8") as fp:
                return fp.read()
        elif isinstance(str_or_filepath, str):
            return str_or_filepath
        else:
            raise ValueError(
                "Check you params Please!!! must be str content or path or Pathlike"
            )

    def _process_content_lines(self, content: str):
        """to process content lines to append content list

        Args:
            content (str): patch content

        Returns:
            list: content modified lines list
        """
        is_content = False
        _lines = []
        temp_lst = []
        _contnet_lines = content.splitlines()
        _content_line_len = len(_contnet_lines)
        for idx, line in enumerate(_contnet_lines):

            if "--- a/" in line:
                is_content = True
                if temp_lst:
                    _lines.append(temp_lst)
                    temp_lst = []

            if is_content:
                if line and (line.startswith("-") or line.startswith("+")):
                    line = line.replace(" ", "")
                    temp_lst.append(line)

            if idx == _content_line_len - 1:
                if temp_lst:
                    _lines.append(temp_lst)

        return _lines

    def compare_result(self, str_or_filepath, other_to_compare):
        """to compare 2 content result are they same

        Args:
            str_or_filepath (any): str or content file path also pathlike
            other_to_compare (any): str or content file path also pathlike

        Returns:
            bool: compare result return True if modified no diff else return False
        """
        self.content = self._get_content(str_or_filepath)
        self.to_compare_content = self._get_content(other_to_compare)

        for content_lines, to_compare_lines in zip_longest(
            self._process_content_lines(self.content),
            self._process_content_lines(self.to_compare_content),
            fillvalue=None,
        ):
            if not all([content_lines, to_compare_lines]):
                return False
            for ln_content, ln_other in zip_longest(content_lines, to_compare_lines):
                if ln_content != ln_other:
                    return False

        return True
